package com.jswl.training.springjpa.netty.messagecode;

import com.jswl.training.springjpa.frame.InternalShared;
import com.jswl.training.springjpa.frame.Nav7BFrame;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;

import java.util.List;


public class Nav7BFramePacketDecoder extends ByteToMessageCodec {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        System.out.println("--------------");
    }


    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List list) throws Exception {
        Nav7BFrame nav7BFrame = new Nav7BFrame();
        byteBuf.markReaderIndex();
        if(byteBuf.readableBytes()<=14){
            return;
        }
        //读取解析字节信息********************************************************************
        //1.读取帧头信息
        for (int i = 0; i < 3; i++) {
            if (byteBuf.readByte() != 0X7B) {
                throw new RuntimeException("字节数据异常");
            }
        }
        //2.读取信源信息
        nav7BFrame.setSourcePrimaryId(byteBuf.readByte());
        nav7BFrame.setSourceSecondaryId(byteBuf.readByte());
        //读取信宿信息
        nav7BFrame.setTargetPrimaryId(byteBuf.readByte());
        nav7BFrame.setTargetSecondaryId(byteBuf.readByte());
        //读取信息类型
        nav7BFrame.setInfoType(byteBuf.readByte());
        //读取信息长度
        int infoLength = byteBuf.readUnsignedShortLE();
        nav7BFrame.setInfoLength(infoLength);
        //读取信息内容类型
        int contentType = byteBuf.readUnsignedShortLE();
        nav7BFrame.setDataType(contentType);
        //信息内容长度(单位bit)
        int contentLength = byteBuf.readUnsignedShortLE();
        nav7BFrame.setBitLength(contentLength);
        //信息内容
        byte[] contentBytes = new byte[contentLength / 8];
        if(byteBuf.readableBytes()<contentBytes.length+2){
            reset(byteBuf);
            return;
        }
        byteBuf.readBytes(contentBytes);
        ByteBuf contentByteBuf = Unpooled.wrappedBuffer(contentBytes);
        nav7BFrame.setDataContent(contentByteBuf);
        //取得校验位信息
        int checkNum = byteBuf.readByte();
        if (checkNum != InternalShared.computeCheckSum(nav7BFrame)) {
            throw new RuntimeException("校验位异常！");
        }
        //帧尾
        byte last = byteBuf.readByte();
        list.add(nav7BFrame);
    }

    public void reset( ByteBuf byteBuf) {
        byteBuf.resetReaderIndex();
    }
}
